//
//  ClassExtension.swift
//  PhotoBrowser
//
//  Created by beisheng03 on 2017/7/14.
//  Copyright © 2017年 beisheng. All rights reserved.
//

import UIKit

// MARK:- NSObject类扩展
extension NSObject{
    
    
  func StringFromClass(classType : AnyClass) -> String{
        
        let string = NSStringFromClass(classType)
        
        
        //          let nsp = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
        
//        let range3 = string.range(of: ".")!
//        
//        let start2 = string.index(range3.lowerBound, offsetBy: 1)
//        
//        let header = string.substring(from: start2)
    
    
        let header = string.components(separatedBy: ".").last
    
        
        return header!
        
    }
    
   func classString() -> String{
        
        let tempString = NSStringFromClass(self as! AnyClass)
        
        
        let classStr = tempString.components(separatedBy: ".").last
        
        
        return classStr!
    }
    
    
    

    
}




extension UIView{

    func addCornerAndBorder(borderColor : UIColor?,borderWidth : CGFloat = 0.0,masksToBounds : Bool = false,cornerRadius : CGFloat = 0.0) {
        if borderColor != nil {
            
            layer.borderColor = borderColor!.cgColor
            layer.borderWidth = borderWidth

        }
        layer.masksToBounds = masksToBounds
        layer.cornerRadius = cornerRadius
    }
    
    
    func performIsLoginJump(aSelector : Selector?,target: UIView?){
        
        if target == nil {
            
            login()
            
            return
        }
        
        if UserViewModel.shared.userIsLogin() == true {


            target!.perform(aSelector)
            
        } else {
            
            login()
            
        }
        
    }
    
    
    func login(){
        
        
        let log = LoginViewController()
        
        
        viewController().present(BaseNavController(rootViewController: log), animated: true, completion: nil)
        
    }


    
    
    func viewController() -> UIViewController! {
        
        var nextResponder = self.next
        
        repeat{
        
            if nextResponder is UIViewController {
                
                return nextResponder as? UIViewController
            }
            
            nextResponder = nextResponder?.next
        
        }while(nextResponder != nil)
        
        
        return nil
        
    }





}


// MARK:- UIButton类扩展
extension UIButton{
    /*
     1.如果在extension中写构造函数则必须写成便利构造函数，便利构造函数有以下两个特点
     在函数前面加上convenience关键字
     需要在构造函数中明确调用self.init()
     */
    
    convenience init(title : String,bgColor : UIColor,fontSize : CGFloat){
        
        self.init()
        
        backgroundColor = bgColor
        titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
        setTitle(title, for: .normal)
        
        
        
    }
    
    
    
    convenience init(imageName:String?,backgroundName:String?){
        self.init()
        
        
        setImage(UIImage(named: imageName ?? ""), for: .normal)
        setImage(UIImage(named: (imageName ?? "") + "_highlighted"), for: .highlighted)
        
        
        guard let bacName = backgroundName else {
            sizeToFit()
            
            return
        }
        setBackgroundImage(UIImage(named: bacName), for: .normal)
        setBackgroundImage(UIImage(named:bacName + "_highlighted"), for: .highlighted)
        sizeToFit()
        
    }
    
    

    
}


// MARK:- UIColor类扩展
extension UIColor{
    
  
   class func randomColor() -> UIColor {
    
        return UIColor(hue: (CGFloat(arc4random() % 256) / 256.0 ), saturation: ( CGFloat(arc4random() % 128) / 256.0 ) + 0.5, brightness: ( CGFloat(arc4random() % 128) / 256.0 ) + 0.5, alpha: 1)
    
    }

    class func colorWith(r : Float,g : Float ,b : Float) -> UIColor {
        return UIColor(colorLiteralRed: r/255.0, green: g/255.0, blue: b/255.0, alpha: 1.0)
    }
    
    
    class func colorWithA(r : Float,g : Float ,b : Float,A : Float) -> UIColor {
        
        return UIColor(colorLiteralRed: r/255.0, green: g/255.0, blue: b/255.0, alpha: A/1.0)
    }
    
    
    class func lighGray() -> UIColor{
        
        return UIColor.colorWithA(r: 211, g: 211, b: 211, A: 1.0)

    }
    
    
    class func dakGray() -> UIColor{
        
        return UIColor.colorWithA(r: 85, g: 85, b: 85, A: 1.0)
        
    }
    
    class func selectTextColor() -> UIColor{
        
        return UIColor(colorLiteralRed: 231/255.0, green: 31/255.0, blue: 25/255.0, alpha: 1.0)
        
    }
    
    
    class func noSelectTextColor() -> UIColor{
        
        return UIColor(colorLiteralRed: 51/255.0, green: 51/255.0, blue: 51/255.0, alpha: 1.0)
        
    }
    
    
    class func lineGray() -> UIColor{
        
        return UIColor.colorWithA(r: 226, g: 226, b: 226, A: 1.0)
    }
    
    
    class func viewBgGrey() -> UIColor{
        
        return UIColor.colorWithA(r: 233, g: 234, b: 235, A: 1.0)

        
    }
    
    
    class func themeColor() -> UIColor{
        
        return UIColor.colorWithA(r: 0, g: 169, b: 254, A: 1.0)
        
    }
    
    
    class func placeholderColor() -> UIColor{
        
        return UIColor.colorWithA(r: 199, g: 199, b: 205, A: 1.0)
        
    }


}



// MARK:- String类扩展
extension String{
    
    func cacheDir() -> String {
        let path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)
        
        return path.first! + "/" + self
    }
    
    func docDir() -> String {
        let path = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        
        return path.first! + "/" + self
        
        
    }
    
    func tmpDir() -> String {
        let path = NSTemporaryDirectory()
        
        return path + "/" + self
        
        
    }
    
    
    func getLabelH(str : String,attributes : [String : Any]?,width : CGFloat) -> CGFloat {
        

        let rect = CGRect(x: 0, y: 0, width: width, height: CGFloat(MAXFLOAT))
        
        
        return  str.boundingRect(with: rect.size, options: [.usesLineFragmentOrigin], attributes: attributes, context: nil).size.height


    }
    
    
    
}


// MARK:- Date类扩展
extension Date{
    
    static func createDateWithString(str:String) -> Date? {
        
        
        let formatter = DateFormatter()
        
        formatter.dateFormat = "EE MM dd HH:mm:ss Z yyyy"
        
        formatter.locale = Locale(identifier: "en")
        
        return formatter.date(from: str)
        
    }
    
    
    
    func descString() -> String? {
        
        let formatter = DateFormatter()
        
        formatter.dateFormat = "EE MM dd HH:mm:ss Z yyyy"
        
        formatter.locale = Locale(identifier: "en")
        
        
        let calendar = Calendar.current
        
        if calendar.isDateInToday(self) {
            //获取时间差
            let interval = Int(Date().timeIntervalSince(self))
            
            if interval < 60 {
                
                return "刚刚"
                
            } else if interval < 3600 {
                
                return "\(interval / 60)分钟前"
                
            }else{
                
                return "\(interval / 3600)小时前"
                
            }
            
            
            
        }else if calendar.isDateInYesterday(self){
            
            formatter.dateFormat = "昨天: HH:mm"
            
            return formatter.string(from: self)
            
        }else{
            
            
            let comps =  calendar.dateComponents([Calendar.Component.year], from: self, to: Date())
            
            _ = comps.year
            
            
            if comps.year! < 1 {
                
                formatter.dateFormat = "MM-dd HH:mm"
                
            } else {
                formatter.dateFormat = "yyyy-MM-dd HH:mm"
                
            }
            
            
            return formatter.string(from: self)
            
            
        }
        
        
        
    }
    
    
}


// MARK:- UIBarButtonItem类扩展
extension UIBarButtonItem{
    
    convenience init(imageName:String?,target:AnyObject?,selector:Selector) {

        let button = UIButton(imageName: imageName ?? nil, backgroundName: nil)
        
        button.addTarget(target, action: selector, for: .touchUpInside)
    

        
        self.init(customView:button)
    }
    
    
    
}






// MARK:- UIImage类扩展
extension UIImage{

    class  func imageWithOriginal(imageName : String) -> UIImage {
        
        let image = UIImage(named: imageName)
        
        return image!.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        
    }
    
    
    class  func defaulImage() -> UIImage {
        
        let image = UIImage(named: "empty_picture")
        
        return image!
        
    }
    
    
    class  func defaulLogoImage() -> UIImage {
        
        let image = UIImage(named: "gray")
        
        return image!
        
    }

    
    class  func defaulIconImage() -> UIImage {
        
        let image = UIImage(named: "defeImage")
        
        return image!
        
    }

    
    class  func imageWithColor(color : UIColor) -> UIImage {
        
        let rect = CGRect(x: 0, y: 0, width: 5, height: 5)
        
        // 1.开启图片上下文
        UIGraphicsBeginImageContext(rect.size)
        
        let context = UIGraphicsGetCurrentContext()
        
        // 使用color演示填充上下文
        context?.setFillColor(color.cgColor);
        // 渲染上下文
        context?.fill(rect);
        
        
        // 4.取出图片
        let newImage =  UIGraphicsGetImageFromCurrentImageContext()
        
        // 结束上下文
        UIGraphicsEndImageContext();
        
        
        return newImage!
        
    }




}

// MARK:- UITextField类扩展
extension UITextField{

    func settingPlaceholder(text : String,color : UIColor,font : UIFont) {
        
        let strM = NSMutableAttributedString(string: text)
        
        
        strM.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, text.characters.count))
        
        
        strM.addAttribute(NSForegroundColorAttributeName, value: color, range: NSMakeRange(0, text.characters.count))
        
        
        
        attributedPlaceholder = strM

        
    }
    
    
    




}




// MARK:- UIImageView类扩展
extension UIImageView{
    
    
    
    
    
    
}






// MARK:- UILabel类扩展
extension UILabel{
    

    
    
    
    
}



// MARK:- UITextView类扩展
extension UITextView{
    

    
    
    
}






